import pandas as pd

df = pd.read_csv("static/data/car_info_pre.csv")
df_outter = df.drop_duplicates(subset=['outter_name'], keep='first')


# 定义函数every_year_car_count，用于获取每一年的汽车数量
def every_year_car_count():
    # 从df_outter中获取year小于等于2023的数据，并按照year进行分组，计算outter_name的数量，并将结果重置索引
    df_line = df_outter[df['year'] <= 2023].groupby('year').count()['outter_name'].reset_index()
    # 获取每一年的年份
    name = df_line.year.values.tolist()
    # 获取每一年的汽车数量
    value = df_line.outter_name.values.tolist()
    # 返回每一年的年份和汽车数量
    return {
        'name': name,
        'value': value
    }


def score_top10():
    df_bar = df_outter.sort_values(by='dcar_score', ascending=False).head(10)
    name = ['-'.join(i) for i in df_bar[['brand_name', 'outter_name']].values]
    value = df_bar.dcar_score.values.tolist()
    return {
        'name': name,
        'value': value
    }


def all_car_tree():
    df_tree = df_outter.groupby('brand_name')['outter_name']
    data = [
        {
            'name': i[0],
            'value': len(i[1]),
            'children': [
                {
                    'name': j,
                    'value': 1,
                } for j in i[1].values
            ]
        } for i in df_tree
    ]
    return {
        'data': data
    }


def brand_word_cloud():
    df_word = df_outter.groupby('brand_name')['outter_name'].count().reset_index()
    data = [
        {
            'name': i[0],
            'value': i[1]
        } for i in df_word.values
    ]
    return {
        'data': data
    }


def price_level_funnel():
    data = [
        {
            'value': 100,
            'name': '全部'
        }
    ]
    data += [
        {
            'value': round(len(df[(df['official_price'] > i * 10)]) / len(df) * 100,2),
            'name': '>{}万'.format(i * 10)
        } for i in range(1, 6)
    ]
    return {
        'data': data
    }
